﻿using IMES.Common.Domain.DariusModel;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using MediatR;
using NPOI.XWPF.UserModel;

namespace Darius.API.Application.Commands.Order
{
    public class OrderSearchHandler : IRequestHandler<OrderSearchCommand, Result>
    {
        private readonly IBaseRepositorys<SaleOrders> saleOrdersRepository;
        private readonly IBaseRepositorys<ApprovalApplications> approvalsApplicationsRepository;
        private readonly ILogger<OrderSearchCommand> logger;

        public OrderSearchHandler(IBaseRepositorys<SaleOrders> saleOrdersRepository, ILogger<OrderSearchCommand> logger, IBaseRepositorys<ApprovalApplications> approvalsApplicationsRepository)
        {
            this.saleOrdersRepository = saleOrdersRepository;
            this.approvalsApplicationsRepository = approvalsApplicationsRepository;
            this.logger = logger;
        }
        /// <summary>
        /// 查询订单
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(OrderSearchCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var result = new Result() { Code = (int)CodeEnum.search };
                var res =( from a in saleOrdersRepository.GetAll()
                          join b in approvalsApplicationsRepository.GetAll() on a.OrderId equals b.OrderId
                          where a.IsDeleted==false&&b.ApprovalStatus==1
                          select new ApplicationOrderDTO
                          {
                              OrderId = a.OrderId,
                              OrderNo = a.OrderNo,
                              OrderNotes = a.OrderNotes,
                              ApprovalStatus=b.ApprovalStatus,
                              IsDeleted=a.IsDeleted,
                          }).ToList();
                if (!string.IsNullOrEmpty(request.OrderNo))
                {
                    res = res.Where(x => x.OrderNo.Contains(request.OrderNo)).ToList();
                }
                result.Data = res;
                result.Messege = "列表查询成功";
                logger.LogInformation("查询订单成功");
                return result;
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "查询订单失败");
                return new Result() { Code = (int)CodeEnum.error, Messege = "查询订单失败" };
            }
        }


    }
}
